<template>
  <div class="dashboard-container">
    <!-- 顶部导航 -->
    <TopNav />
    <!-- <div class="top-nav">
      <div class="nav-links">
        <RouterLink to="/active" class="nav-button">活动中心</RouterLink>
        <RouterLink to="/SelectActive" class="nav-button">选择活动</RouterLink>
        <RouterLink to="/Test" class="nav-button">测试练习</RouterLink>
        <RouterLink to="/Search" class="nav-button">单词搜索</RouterLink>
        <RouterLink to="/Composition" class="nav-button">作文练习</RouterLink>
        <RouterLink to="/NewWord" class="nav-button">新词学习</RouterLink>
      </div>
      <button class="logout-button" @click="logout">
        <i class="fas fa-sign-out-alt"></i> 退出登录
      </button>
    </div> -->

    <!-- 主仪表盘内容 -->
    <div class="dashboard-content">
      <!-- 用户概览卡片 -->
      <div class="user-overview">
        <div class="welcome-card">
          <div class="avatar">
            <i class="fas fa-user-circle"></i>
          </div>
          <div class="user-info">
            <h2>欢迎回来, {{ username }}</h2>
            <p>今日已学习 {{ todayLearned }} 个单词</p>
            <div class="streak">
              <i class="fas fa-fire"></i>
              <span>连续签到: {{ checkinDays }} 天</span>
            </div>
          </div>
        </div>

        <div class="stats-grid">
          <div class="stat-card" style="--card-color: #4e73df;">
            <div class="stat-icon">
              <i class="fas fa-book-open"></i>
            </div>
            <div class="stat-info">
              <h3>已学习</h3>
              <p>{{ learnedCount }} 个</p>
            </div>
          </div>

          <div class="stat-card" style="--card-color: #1cc88a;">
            <div class="stat-icon">
              <i class="fas fa-tasks"></i>
            </div>
            <div class="stat-info">
              <h3>今日目标</h3>
              <p>{{ todayGoal }}/{{ dailyGoal }} 个</p>
            </div>
          </div>

          <div class="stat-card" style="--card-color: #f6c23e;">
            <div class="stat-icon">
              <i class="fas fa-clock"></i>
            </div>
            <div class="stat-info">
              <h3>学习时间</h3>
              <p>{{ studyTime }} 分钟</p>
            </div>
          </div>

          <div class="stat-card" style="--card-color: #e74a3b;">
            <div class="stat-icon">
              <i class="fas fa-exclamation-circle"></i>
            </div>
            <div class="stat-info">
              <h3>待学习</h3>
              <p>{{ unlearnedCount }} 个</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 数据可视化区域 -->
      <div class="visualization-section">
        <!-- 学习进度图表 -->
        <div class="chart-card">
          <h3><i class="fas fa-chart-line"></i> 学习进度</h3>
          <div class="chart-container">
            <canvas ref="progressChart"></canvas>
          </div>
        </div>

        <!-- 签到日历 -->
        <div class="chart-card">
          <h3><i class="fas fa-calendar-alt"></i> 签到日历</h3>
          <div class="calendar">
            <div class="calendar-header">
              <button @click="prevMonth"><i class="fas fa-chevron-left"></i></button>
              <h4>{{ currentMonth }}</h4>
              <button @click="nextMonth"><i class="fas fa-chevron-right"></i></button>
            </div>
            <div class="calendar-grid">
              <div v-for="day in calendarDays" :key="day.date"
                :class="['day', { 'checked': day.checked, 'today': day.isToday }]">
                {{ day.day }}
                <i v-if="day.checked" class="fas fa-check"></i>
              </div>
            </div>
          </div>
        </div>

        <!-- 学习时间分布 -->
        <div class="chart-card">
          <h3><i class="fas fa-clock"></i> 学习时间分布</h3>
          <div class="chart-container">
            <canvas ref="timeChart"></canvas>
          </div>
        </div>

        <!-- 单词掌握程度 -->
        <div class="chart-card">
          <h3><i class="fas fa-brain"></i> 单词掌握程度</h3>
          <div class="chart-container">
            <canvas ref="masteryChart"></canvas>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { Chart, registerables } from 'chart.js';
import TopNav from "../../components/TopNav.vue";

// 注册Chart.js组件
Chart.register(...registerables);

const router = useRouter();

// 模拟数据 - 实际应用中应从API获取
const username = ref('学习者');
const checkinDays = ref(7);
const learnedCount = ref(356);
const unlearnedCount = ref(124);
const todayLearned = ref(15);
const dailyGoal = ref(20);
const todayGoal = ref(15);
const studyTime = ref(86);
const wordsTotle = ref(500);

// 日历相关数据
const currentDate = ref(new Date());
const calendarDays = ref(generateCalendarDays());

// 图表引用
const progressChart = ref(null);
const timeChart = ref(null);
const masteryChart = ref(null);

// 生成日历天数
function generateCalendarDays() {
  const year = currentDate.value.getFullYear();
  const month = currentDate.value.getMonth();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const firstDay = new Date(year, month, 1).getDay();

  const days = [];

  // 填充空白
  for (let i = 0; i < firstDay; i++) {
    days.push({ day: '', date: null, checked: false, isToday: false });
  }

  // 填充日期
  const today = new Date();
  for (let i = 1; i <= daysInMonth; i++) {
    const date = new Date(year, month, i);
    days.push({
      day: i,
      date: date,
      checked: Math.random() > 0.3, // 模拟签到数据
      isToday: date.toDateString() === today.toDateString()
    });
  }

  return days;
}

// 月份导航
function prevMonth() {
  currentDate.value = new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth() - 1,
    1
  );
  calendarDays.value = generateCalendarDays();
}

function nextMonth() {
  currentDate.value = new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth() + 1,
    1
  );
  calendarDays.value = generateCalendarDays();
}

// 当前月份显示
const currentMonth = computed(() => {
  return currentDate.value.toLocaleString('default', {
    month: 'long',
    year: 'numeric'
  });
});

// 初始化图表
onMounted(() => {
  fetchStats();
  // 学习进度图表
  new Chart(progressChart.value, {
    type: 'line',
    data: {
      labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
      datasets: [{
        label: '已学单词',
        data: [50, 100, 150, 220, 280, 356],
        borderColor: '#4e73df',
        backgroundColor: 'rgba(78, 115, 223, 0.05)',
        tension: 0.4,
        fill: true
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: {
          display: false
        }
      },
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  });

  // 学习时间分布图表
  new Chart(timeChart.value, {
    type: 'doughnut',
    data: {
      labels: ['早晨', '上午', '下午', '晚上', '深夜'],
      datasets: [{
        data: [15, 30, 25, 20, 10],
        backgroundColor: [
          '#4e73df',
          '#1cc88a',
          '#36b9cc',
          '#f6c23e',
          '#e74a3b'
        ],
        borderWidth: 0
      }]
    },
    options: {
      responsive: true,
      cutout: '70%',
      plugins: {
        legend: {
          position: 'bottom'
        }
      }
    }
  });

  // 单词掌握程度图表
  new Chart(masteryChart.value, {
    type: 'bar',
    data: {
      labels: ['掌握', '熟悉', '一般', '生疏', '遗忘'],
      datasets: [{
        label: '单词数量',
        data: [120, 90, 70, 50, 26],
        backgroundColor: [
          '#1cc88a',
          '#36b9cc',
          '#f6c23e',
          '#f6c23e',
          '#e74a3b'
        ]
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: {
          display: false
        }
      },
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  });
});

// const logout = () => {
//   localStorage.removeItem('token');
//   router.push('/');
// };


//获取用户数据
// import { ref, onMounted } from 'vue';
import { getUserStats } from '../../api/authService.js';  // 导入 getUserStats 函数

const stats = ref(null);   // 用于存储学习统计信息
const error = ref(null);   // 用于存储错误信息

// 获取存储在 localStorage 中的用户 ID
const userId = localStorage.getItem('userId');

// 获取用户学习统计信息的函数
const fetchStats = async () => {
  if (!userId) {
    error.value = '用户 ID 丢失，请先登录';
    return;
  }

  const result = await getUserStats(userId); // 调用 getUserStats

  if (result.success) {
    stats.value = result.stats;  // 更新学习统计信息
  } else {
    error.value = result.message;  // 显示错误信息
  }
  console.log(stats.value);
  learnedCount.value = stats.value.learned_words;
  unlearnedCount.value = stats.value.unlearned_words;
  wordsTotle.value = stats.value.total_words;
  username.value = stats.value.username;
};





import { inject } from "vue";

const theme = inject("theme");
const setTheme = (newTheme) => {
  theme.value = newTheme; // 更新全局主题
};
</script>

<style scoped lang="scss">
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');

.dashboard-container {
  min-height: 100vh;
  background-color: var(--bg-color);
  color: var(--text-color);
}

// .top-nav {
//   display: flex;
//   justify-content: space-between;
//   align-items: center;
//   padding: 1rem 2rem;
//   background-color: var(--bg-color);

//   // background: linear-gradient(135deg, #1e3c72, #2a5298);
//   box-shadow: 0 0.15rem 0.75rem 0 var(--shadow-color);

//   .nav-links {
//     display: flex;
//     gap: 1rem;
//   }

//   .nav-button {
//     padding: 0.5rem 1rem;
//     // color: rgba(255, 255, 255, 0.8);
//     text-decoration: none;
//     border-radius: 0.35rem;
//     transition: all 0.3s;
//     color: var(--text-color);

//     &:hover {
//       color: var(--card-bg);
//       background: rgba(0, 0, 0, 0.2);
//     }
//   }

//   .logout-button {
//     padding: 0.5rem 1rem;
//     background: #126268;
//     color: white;
//     border: none;
//     border-radius: 0.35rem;
//     cursor: pointer;
//     transition: all 0.3s;

//     &:hover {
//       background: #be2617;
//     }
//   }
// }

.dashboard-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.user-overview {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 1.5rem;
  margin-bottom: 1.5rem;

  @media (max-width: 768px) {
    grid-template-columns: 1fr;
  }
}

.welcome-card {
  display: flex;
  align-items: center;
  padding: 1.5rem;
  background: var(--bg-color);
  border-radius: 0.35rem;
  box-shadow: 0 0.15rem 0.75rem 0 var(--shadow-color);

  .avatar {
    font-size: 3rem;
    color: #4e73df;
    margin-right: 1.5rem;
  }

  .user-info {
    h2 {
      margin: 0 0 0.5rem;
      font-size: 1.25rem;
      color: #4e73df;
    }

    p {
      margin: 0 0 0.5rem;
      color: #858796;
    }

    .streak {
      display: flex;
      align-items: center;
      color: #f6c23e;

      i {
        margin-right: 0.5rem;
      }
    }
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1rem;

  @media (min-width: 576px) {
    grid-template-columns: repeat(4, 1fr);
  }
}

.stat-card {
  display: flex;
  padding: 1rem;
  background: var(--bg-color);
  border-radius: 0.35rem;
  box-shadow: 0 0.15rem 0.75rem 0 var(--shadow-color);
  border-left: 0.25rem solid var(--card-color);

  .stat-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 3rem;
    height: 3rem;
    background: rgba(var(--card-color), 0.1);
    color: var(--card-color);
    border-radius: 50%;
    font-size: 1.25rem;
    margin-right: 1rem;
  }

  .stat-info {
    h3 {
      margin: 0 0 0.25rem;
      font-size: 0.9rem;
      color: #858796;
      font-weight: 600;
    }

    p {
      margin: 0;
      font-size: 1.25rem;
      font-weight: 700;
      color: #5a5c69;
    }
  }
}

.visualization-section {
  display: grid;
  grid-template-columns: repeat(1, 1fr);
  gap: 1.5rem;

  @media (min-width: 992px) {
    grid-template-columns: repeat(2, 1fr);
  }
}

.chart-card {
  padding: 1.5rem;
  background: var(--bg-color);
  border-radius: 0.35rem;
  box-shadow: 0 0.15rem 0.75rem 0 var(--shadow-color);

  h3 {
    margin: 0 0 1.5rem;
    font-size: 1rem;
    color: #4e73df;
    display: flex;
    align-items: center;

    i {
      margin-right: 0.5rem;
    }
  }

  .chart-container {
    position: relative;
    height: 250px;
  }
}

.calendar {
  .calendar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;

    button {
      background: none;
      border: none;
      color: #4e73df;
      cursor: pointer;
      padding: 0.5rem;

      &:hover {
        color: #224abe;
      }
    }

    h4 {
      margin: 0;
      font-size: 1rem;
    }
  }

  .calendar-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 0.5rem;

    .day {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 2.5rem;
      border-radius: 50%;
      font-size: 0.85rem;
      position: relative;

      &.checked {
        background: rgba(28, 200, 138, 0.1);
        color: #1cc88a;
      }

      &.today {
        font-weight: bold;
        color: #4e73df;
      }

      i {
        position: absolute;
        bottom: 0;
        font-size: 0.6rem;
      }
    }
  }
}
</style>